import React from 'react';
import { Button, message } from 'antd';
import Api from 'Utils/api';
import './../index.scss';

// this.props.type  接受一个上传类型
// this.props.path  接受一个Api path
class ImportData extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    };
    this.handleImport = ::this.handleImport;
    this.updataFile = ::this.updataFile;
  }
  componentDidMount() {
  }
  handleImport() {
    const inputEle = document.getElementById('import-file');
    inputEle.addEventListener('change', () => {
      const file = inputEle.files[0];
      this.updataFile(file);
    });
    inputEle.click();
  }
  updataFile(file) {
    this.setState({ loading: true });
    const formData = new window.FormData();
    formData.append('import_file', file, file.name);
    const api = new Api({
      method: 'POST',
      path: `${this.props.path || '/errPath'}`,
      noHeader: true,
      data: formData,
      success: () => {
        this.setState({ loading: false });
        message.success('导入成功');
        this.props.init();
      },
      error: (err) => {
        this.setState({ loading: false });
        message.error(err);
      }
    });
    api.run();
  }
  render() {
    return (
      <div>
        <Button className="search-btn" onClick={this.handleImport} loading={this.state.loading}>
          <img src="images/icon_data_import.png" alt="导入" />
          导入CSV
        </Button>
        <input
          className="import-file"
          id="import-file"
          type="file"
          accept={this.props.type || '.csv'}
        />
      </div>
    );
  }
}

export default ImportData;
